export default class Heading {

    name: string = '';
    /**0表示根 */
    level: number = 0;
    /**行号 */
    line: number = 0;

    parent: Heading = null;
    children: Heading[] = [];

    /**是否展开 */
    isExpand: boolean = true;

    constructor(name: string = '', level: number = 0, line: number = -1) {
        this.name = name;
        this.level = level;
        this.line = line;
    }

    addChild(heading: Heading) {
        this.children.push(heading);
        heading.parent = this;
    }

    /**回溯级别为level的父标题 */
    backtrackParent(level: number): Heading {
        if (level >= this.level) return null;

        let parent = this.parent;
        while (parent.level != 0) {
            if (parent.level == level) break;
            parent = parent.parent;
        }
        return parent;
    }

    getAllHeadings(ignoreFold: boolean = false): Heading[] {
        let headings: Heading[] = [];

        if (this.level == 0) {
            for (let child of this.children) {
                headings.push(...child.getAllHeadings());
            }
        }
        else {
            headings.push(this);

            if (ignoreFold || this.isExpand) {
                for (let child of this.children) {
                    headings.push(...child.getAllHeadings(ignoreFold));
                }
            }
        }

        return headings;
    }

    /**没有子标题 */
    isLeaf(): boolean { return this.children.length == 0; }

    /**有父标题 */
    haveParent(): boolean { return this.level > 1; }

    toggleFold() { this.isExpand = !this.isExpand; }

    equal(other: Heading): boolean { return this.line === other.line; }

    findParentByLevel(level: number): Heading {
        if (this.level <= level) return this;

        let it = this.parent;
        while (it.level != 1) {
            if (it.level <= level) break;
            it = it.parent;
        }

        return it;
    }
}
